﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Citi.PTSConsolidation.Domain;
using Citi.PTSConsolidation.WebUi.Models;

namespace Citi.PTSConsolidation.WebUi.Controllers
{
    public class ProgramController : Controller
    {
        public ActionResult Index()
        {
            var programs = new Program().SelectAll<Program>().OrderBy(x=> x.Id);

            return View(ProgramModel.CreateModel(programs));
        }

        public ActionResult Exceptions()
        {
            var programs = new Program().SelectAll<Program>().Where(x=> x.ProgramOwner == null);

            return View(ProgramModel.CreateModel(programs));
        }

        [HttpPost]
        public ActionResult Exceptions(FormCollection collection)
        {
            var keys = collection.AllKeys.Where(x => x.StartsWith("ProgramOwner"));
            var programs = new Program().SelectAll<Program>().Where(x=> x.ProgramOwner == null);

            foreach (var key in keys)
            {
                var id = key.Replace("ProgramOwner", string.Empty);
                var programOwner = collection[key];

                if (string.IsNullOrWhiteSpace(programOwner)) continue;

                var program = programs.FirstOrDefault(x => x.Id == id);
                program.ProgramOwner = programOwner;
                program.Save(program);
            }

            programs = programs.Where(x=> x.ProgramOwner == null);

            return View(ProgramModel.CreateModel(programs));
        }
    }
}
